package com.lucker.controller.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.apache.bcel.generic.RET;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.lucker.cds.model.CMUser;
import com.lucker.common.enums.CheckCodeType;
import com.lucker.common.enums.UserLevel;
import com.lucker.common.enums.UserTokenType;
import com.lucker.common.request.RequestContext;
import com.lucker.common.util.Constant;
import com.lucker.common.util.LocalUtil;
import com.lucker.common.util.RequestUtil;
import com.lucker.common.util.StringUtil;
import com.lucker.controller.BaseController;
import com.lucker.ds.model.MUser;
import com.lucker.ds.model.SysCheckCode;
import com.lucker.ds.model.UserToken;
import com.lucker.framework.constant.ResponseBaseModel;
import com.lucker.framework.constant.ResponseResultModel;
import com.lucker.framework.constant.UserRoleType;
import com.lucker.framework.exception.BaseServiceException;
import com.lucker.service.checkcode.SysCheckCodeService;
import com.lucker.service.user.MuserService;
import com.lucker.service.wx.WxService;
import com.lucker.vo.VUser;

@Controller()
@RequestMapping(value = "user")
public class UserController extends BaseController {
	
	@Autowired
	private MuserService muserService;
	@Autowired
	private WxService wxService;
	
	@Autowired
	SysCheckCodeService sysCheckCodeService;
	
	
	@RequestMapping(value="registertreaty",method=RequestMethod.POST)
	public @ResponseBody  ResponseEntity<?> registerTreaty(){
		Map<String, Object> retMap = new HashMap<String , Object>();
		try {
			List<String> treatyTextList = new ArrayList<String>();
			for(int i = 0 ; i < 10 ; i++) {
				treatyTextList.add((i + 1) + ".  用户注册协议内容 " + (i+1));
			}
			retMap.put("title", "用户注册协议");
			retMap.put("list", treatyTextList);
			return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(retMap),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("发送注册验证码异常  ", e);
			return new ResponseEntity<>(new ResponseBaseModel(29001,"发送短信码失败"), HttpStatus.OK);
		}	
	}
	
	
	
	@RequestMapping(value="sendregistercode",method=RequestMethod.POST)
	public @ResponseBody  ResponseEntity<?> sendRegisterCheckCode(@RequestBody SysCheckCode _checkCode){
		try {
			if(_checkCode == null) {
				return new ResponseEntity<>(new ResponseBaseModel(29001,"参数为空"), HttpStatus.OK);
			}
			if(StringUtils.isBlank(_checkCode.getMobile())) {
				return new ResponseEntity<>(new ResponseBaseModel(29001,"参数为空"), HttpStatus.OK);
			}
			
			MUser u = new MUser();
			u.setUserName(_checkCode.getMobile());
			List<MUser> ulist = muserService.queryAll(u);
			if(CollectionUtils.isNotEmpty(ulist)) {
				return new ResponseEntity<>(new ResponseBaseModel(29001,"该手机号已经注册"), HttpStatus.OK);
			}
			
			
			sysCheckCodeService.sendCheckCode(_checkCode.getMobile(),CheckCodeType.REG_TYPE_SMS_CODE);
		}catch(Exception e) {
			this.getLoger().error("发送注册验证码异常  ", e);
			return new ResponseEntity<>(new ResponseBaseModel(29001,"发送短信码失败"), HttpStatus.OK);
		}	
		return new ResponseEntity<>(new ResponseResultModel<MUser>(null),HttpStatus.OK);
	}
	
	
	@RequestMapping(value="register",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> register(HttpServletRequest request,@RequestBody VUser _user) {
		try {
			if(_user != null) {
				if(!StringUtil.equals("127.0.0.1", getIP(request))) {
					if(LocalUtil.getLocal(getIP(request)) != null)
					_user.setDefualtDomainName(LocalUtil.getLocal(getIP(request)).getProvince().getCnName());
				}
				if(_user.getRoleId() == null || _user.getRoleId() < 1) {
					_user.setRoleId(UserLevel.normal.getCode());
				}
				int ret = muserService.registerUser(_user,_user.getCheckCode());
				if(ret > 0) {
					return new ResponseEntity<>(new ResponseResultModel<String>("ok"),HttpStatus.OK);
				}else {
					return new ResponseEntity<>(new ResponseBaseModel(29001,"注册失败!"), HttpStatus.OK);
				}
			}
		}catch(Exception e) {
			this.getLoger().error("注册异常  ", e);
			return new ResponseEntity<>(new ResponseBaseModel(29001,e.getMessage()), HttpStatus.OK);
		}
		return new ResponseEntity<>(new ResponseResultModel<MUser>(null),HttpStatus.OK);
	}
	
	
	@RequestMapping(value="login",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> login(@RequestBody MUser user, HttpServletRequest req) {
		try {
			
			
			CMUser cuser = muserService.login(user,getRequestHeader(req));
			return new ResponseEntity<>(new ResponseResultModel<CMUser>(cuser),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("登录异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value="wxlogin",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> wxlogin(@RequestBody RequestContext<String> reqBody) {
		try {			
			getLoger().error("获取CODE :" + reqBody.getRequestBody().toString());
			String opid = wxService.requestWxSession(reqBody.getRequestBody().toString()).getOpenid();
			if(StringUtils.isBlank(opid)) {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"获取用户OPENID失败!"), HttpStatus.OK);
			}
			MUser _muser = new MUser();
			_muser.setUserWxOpenid(opid);
			List<MUser> user_list = muserService.queryAll(_muser);
			MUser _loginUser = null;
			if(CollectionUtils.isNotEmpty(user_list)) {
				if(user_list.size() > 1) {
					getLoger().error("用户OPENID包含多条数据，请联系技术处理! , OPENID: {}" , opid);
					throw new Exception("用户OPENID包含多条数据，请联系技术处理!");
				}
				_loginUser = user_list.get(0);
			}else {
				return new ResponseEntity<>(new ResponseBaseModel(29101,"该用户未注册!"), HttpStatus.OK);
			}
			if(_loginUser.getIsFreeze()) {
				throw new Exception("该用用已被系统冻结账户,目前不允许登录!");
			}
			if(_loginUser.getIsDelete()) {
				throw new Exception("该用用已被系统禁用,不允许登录!");
			}
			return new ResponseEntity<>(new ResponseResultModel<MUser>(_loginUser),HttpStatus.OK);
		}catch(Exception e) {
			this.getLoger().error("登录异常 {} , {}", e.getMessage(),e);
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
	
	
	@RequestMapping(value="isregister",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> isRegister(@RequestBody MUser u) {
		Map<String,Object> _map = null;
		if(u == null || StringUtils.isBlank(u.getUserName())) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"用户名参数为空"), HttpStatus.OK);
		}
		MUser _u = new MUser();
		_u.setUserName(u.getUserName());
		_u.setIsDelete(Boolean.FALSE);
		List<MUser> _ulist = muserService.queryAll(_u);
		if(CollectionUtils.isEmpty(_ulist)) {
			_map = new HashMap<String,Object>();
			_map.put("isregister", false);
			return new ResponseEntity<>(new ResponseResultModel<Map<String,Object>>(_map),HttpStatus.OK);
		}
		if(_ulist.size() > 0) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"系统错误,该用户账号已存在"), HttpStatus.OK);
		}
		return null;
	}
	
	/***
	 * 微信登录绑定手机号
	 * @return
	 */
	@RequestMapping(value="bind_user_account",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> bindUserInfo(){
		return null;
		
	}
	
	
	@RequestMapping(value="check_code",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> checkCode(@RequestBody SysCheckCode checkCode) {
		try {
			
			if(sysCheckCodeService.checkCode(checkCode.getMobile(), checkCode.getCode(), CheckCodeType.REG_TYPE_SMS_CODE)) {
				return new ResponseEntity<>(new ResponseBaseModel(10000,"验证成功"), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseBaseModel(29002,"验证失败"), HttpStatus.OK);
			}
			
		}catch(Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
		}
	}
		
	/***
	 * 发送登录验证码
	 * @param checkCode ： 包含mobile手机号，用于接收登录验证码
	 * @param req
	 * @return
	 */
	@RequestMapping(value="send_login_code",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> send_login_code(@RequestBody SysCheckCode checkCode, HttpServletRequest req) {

		if(checkCode == null) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"参数不能为空"), HttpStatus.OK);
		}
		
		if(StringUtils.isBlank(checkCode.getMobile())) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"参数不能为空"), HttpStatus.OK);
		}
		try {
			
			sysCheckCodeService.sendCheckCode(checkCode.getMobile(),CheckCodeType.LOGIN_SMS_CODE);
			return new ResponseEntity<>(new ResponseBaseModel(10000,"发送成功"), HttpStatus.OK);
		}catch(Exception e) {
			getLoger().error("发送登录验证码错误 : {} " , e );
			return new ResponseEntity<>(new ResponseBaseModel(29002, "发送登录验证码错误" ), HttpStatus.OK);
		}
	}
	
	//UserToken utk = userTokenService.reSetUserToken(user.getId(), UserTokenType.USER_TOKEN_LOGIN, requestHeader.getAppType());
	
	/***
	 * 短信验证码登录
	 * @param checkCode ： 包含mobile手机号，用于接收登录验证码
	 * @param req
	 * @return
	 */
	@RequestMapping(value="checkcode_login",method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> checkcode_login(@RequestBody SysCheckCode checkCode, HttpServletRequest req) {

		if(checkCode == null) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"参数不能为空"), HttpStatus.OK);
		}
		
		if(StringUtils.isBlank(checkCode.getMobile())) {
			return new ResponseEntity<>(new ResponseBaseModel(29002,"参数不能为空"), HttpStatus.OK);
		}
		try {
			MUser u = new MUser();
			u.setUserName(checkCode.getMobile());
			List<MUser> ulist = muserService.queryAll(u);
			if(CollectionUtils.isEmpty(ulist)) {
				return new ResponseEntity<>(new ResponseBaseModel(29001,"该手机号还未注册"), HttpStatus.OK);
			}
			checkCode.setUserId(ulist.get(0).getId());
			return muserService.checkCodeLogin(checkCode, getRequestHeader(req));
		}catch(Exception e) {
			getLoger().error("发送登录验证码错误 : {} " , e );
			return new ResponseEntity<>(new ResponseBaseModel(29002, "发送登录验证码错误" ), HttpStatus.OK);
		}
	}
	
	
	

}